<template>
  <div>
    <ay-aside :page-info="pageInfo" />
    <div class="app-container">
      <div class="filter-container">
        <el-button v-waves class="filter-item refresh-btn" icon="el-icon-refresh" @click="handleRefresh" />
        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button v-waves class="filter-item" type="danger" icon="el-icon-delete" :disabled="disabledDelBtn" @click="handleDelete(delIdArr)">
          删除
        </el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        fit
        highlight-current-row
        style="width: 100%;"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="30"
          :selectable="selectInit"
        />
        <el-table-column label="#" align="center" width="80">
          <template slot-scope="{$index}">
            <span>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="菜单名称" min-width="80px">
          <template slot-scope="{$index, row}">
            <span v-show="!row.expand" style="cursor: pointer;" :class="{'icon-catalog':row.type == 0,'icon-menu':row.type == 1,'icon-button':row.type == 2 }" @click="toggleMenu($index, row)"><i v-show="row.list && row.list.length !== 0" class="el-icon-arrow-right" style="margin-right:4px;" />{{ row.name }}</span>
            <span v-show="row.expand" style="cursor: pointer;" :class="{'icon-catalog':row.type == 0,'icon-menu':row.type == 1,'icon-button':row.type == 2 }" @click="toggleMenu($index, row)"><i v-show="row.list && row.list.length !== 0" class="el-icon-arrow-down" style="margin-right:4px;" />{{ row.name }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="父级id" align="center" width="95">
          <template slot-scope="{row}">
            <span>{{ row.parentId }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="图标" align="center" width="80px">
          <template slot-scope="{row}">
            <svg-icon :icon-class="row.icon || ''" class="meta-item__icon" />
          </template>
        </el-table-column>
        <el-table-column label="规则" min-width="80px">
          <template slot-scope="{row}">
            <span>{{ row.url }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权重" align="center" width="95">
          <template slot-scope="{row}">
            <span>{{ row.orderNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.type == 0? 'success': row.type == 1? '':'warning'">
              {{ row.type == 0? '目录': row.type == 1? '菜单':'按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="handleUpdate(row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete([row.menuId])" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @open="openDialog">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="类型：" prop="type">
            <template>
              <el-radio v-model="temp.type" :label="0" @change="handleChangeRadio">目录</el-radio>
              <el-radio v-model="temp.type" :label="1" @change="handleChangeRadio">菜单</el-radio>
              <el-radio v-model="temp.type" :label="2" @change="handleChangeRadio">按钮</el-radio>
            </template>
          </el-form-item>
          <el-form-item label="父级：" prop="parentId">
            <!-- 调用树形下拉框组件 -->
            <SelectTree
              :props="props"
              :options="optionData"
              :value="temp.parentId"
              :clearable="isClearable"
              :accordion="isAccordion"
              :disabled="isDisabled"
              @getValue="getSelecTreeId($event)"
            />
          </el-form-item>
          <el-form-item :label="temp.type == 0 ? '目录名称' : (temp.type == 1? '菜单名称': '按钮名称')" prop="name">
            <el-input v-model="temp.name" placeholder="输入菜单名称" />
          </el-form-item>
          <el-form-item label="规则：" prop="url">
            <el-input v-model="temp.url" placeholder="输入菜单规则" />
          </el-form-item>
          <el-form-item v-show="temp.type !== 2" label="图标：">
            <svg-icon v-show="temp.icon !== 'no-pic'" :icon-class="temp.icon || 'no-pic'" style="margin-left: 20px" />
            <span v-show="temp.icon == 'no-pic'" style="margin-left: 20px">无</span>
            <el-button icon="el-icon-search" style="margin-left: 20px" type="mini" @click="dialogIconVisible = true">选择图标</el-button>
            <el-button icon="el-icon-close" style="margin-left: 20px" type="mini" @click="temp.icon = 'no-pic'">清除</el-button>
          </el-form-item>
          <el-form-item label="权重：" prop="orderNum">
            <el-input v-model="temp.orderNum" type="number" />
          </el-form-item>
          <!-- <el-form-item label="菜单说明">
            <el-input v-model="temp.notes" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="输入菜单说明，将用到菜单页面说明上" />
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <template>
              <el-radio v-model="temp.status" :label="1">正常</el-radio>
              <el-radio v-model="temp.status" :label="0">冻结</el-radio>
            </template>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>
      <el-dialog title="选择图标" :visible.sync="dialogIconVisible">
        <Icons @selectIcon="selectIcon" />
      </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="dialogDelVisible"
        width="30%"
      >
        <span>确定删除数据？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDelVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getMenuList, selectMenuList, saveMenuInfo, updateMenuInfo, deletMenuInfo } from '@/api/privilege'
import { deepClone } from '@/utils/index'
import waves from '@/directive/waves' // waves directive
import AyAside from '@/components/Aside'
import SelectTree from '@/components/TreeSelect'
import Icons from '@/components/Icons'
export default {
  name: 'Menu',
  components: { SelectTree, AyAside, Icons },
  directives: { waves },
  filters: {},
  data() {
    return {
      isClearable: true, // 下拉树可清空（可选）
      isAccordion: true, // 下拉树可收起（可选）
      isDisabled: false, // 下拉树可禁用（可选）
      props: { // 下拉树配置项（必选）
        value: 'menuId',
        label: 'name',
        children: 'children'
      },
      disabledDelBtn: true,
      dialogIconVisible: false,
      dialogDelVisible: false,
      pageInfo: {},
      list: null,
      listLoading: true,
      selectList: null,
      delIdArr: [],
      temp: {
        menuId: undefined,
        type: 0,
        parentId: '0',
        name: '',
        url: '',
        icon: 'no-pic',
        orderNum: 0,
        notes: '',
        status: 1
      },
      tempDialog: {
        parentId: '0'
      },
      tableData: [],
      toggleSwitch: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        name: [{ required: true, message: '菜单名称不能为空', trigger: 'change' }],
        url: [{ required: true, message: '菜单规则不能为空', trigger: 'change' }],
        parentId: [{ required: true, message: '父级不能为空', trigger: 'change' }]
      },
      len: 0
    }
  },
  computed: {
    /* 转树形数据 */
    optionData() {
      if (this.selectList) {
        const cloneData = deepClone(this.selectList) // 对源数据深度克隆
        return cloneData.filter(father => {
          const branchArr = cloneData.filter(child => father.menuId === child.parentId) // 返回每一项的子级数组
          branchArr.length > 0 ? father.children = branchArr : '' // 给父级添加一个children属性，并赋值
          return father.parentId == null // 返回第一层
        })
      }
      return []
    }
  },
  created() {
    this.getList()
    this.pageInfo = this.$route.meta
  },
  methods: {
    // 弹窗，类型改变
    handleChangeRadio(label) {
      this.optionChangeRadio(label)
    },
    // 弹窗，类型改变操作
    optionChangeRadio(val) {
      switch (val) {
        case 0:
          this.temp.type = 0
          this.temp.parentId = '0'
          this.isDisabled = true
          break
        case 1:
          this.temp.parentId = this.tempDialog.parentId
          this.isDisabled = false
          break
        case 2:
          this.temp.parentId = this.tempDialog.parentId
          this.isDisabled = false
          break
      }
    },
    // 切换菜单
    toggleMenu(index, row) {
      row.expand = !row.expand
      if (row.expand) {
        if (row.list && row.list.length > 0) {
          this.tableData[index].nodeLen = row.list.length
          const loop = (row) => {
            for (const i in this.tableData) {
              if (row.parentId === this.tableData[i].menuId) {
                this.tableData[i].nodeLen += row.list.length
                loop(this.tableData[i])
              }
            }
          }
          loop(row)
          this.tableData.splice(index + 1, 0, ...row.list)
        }
      } else {
        if (row.list && row.list.length > 0) {
          const loopD = (row) => {
            for (const i in this.tableData) {
              if (row.menuId === this.tableData[i].parentId) {
                this.tableData[i].expand = false
                loopD(this.tableData[i])
              }
            }
          }
          loopD(row)
          this.tableData.splice(index + 1, this.tableData[index].nodeLen)
          this.tableData[index].nodeLen -= row.list.length
          const loop = (row) => {
            for (const i in this.tableData) {
              if (row.parentId === this.tableData[i].menuId) {
                this.tableData[i].nodeLen -= row.list.length
                loop(this.tableData[i])
              }
            }
          }
          loop(row)
        }
      }
    },
    // 表格列样式
    tableRowClassName({ row, rowIndex }) {
      if (row.isMenu === 0) {
        return 'gray-row'
      }
      return ''
    },
    // 禁用选择框
    selectInit(row, index) {
      if (row.isMenu === 0) {
        return false
      } else {
        return true
      }
    },
    // 下拉树值选择
    getSelecTreeId(value) {
      this.temp.parentId = value
    },
    // 图标选择
    selectIcon(val) {
      this.dialogIconVisible = false
      this.temp.icon = val
    },
    // 构造树
    buildTree(nodeList) {
      const cloneData = deepClone(nodeList) // 对源数据深度克隆
      return cloneData.filter(father => {
        const branchArr = cloneData.filter(child => father.menuId === child.parentId) // 返回每一项的子级数组
        branchArr.length > 0 ? father.list = branchArr : '' // 给父级添加一个children属性，并赋值
        return father.parentId === '0' // 返回第一层
      })
    },
    // 弹窗显示时
    openDialog() {
      this.tempDialog.parentId = this.temp.parentId
      this.optionChangeRadio(this.temp.type)
    },
    // 获取表格数据接口
    getList() {
      this.listLoading = true
      return new Promise((resolve, reject) => {
        getMenuList({}).then(response => {
          this.list = response.data
          // const cloneData = deepClone(this.list)
          selectMenuList().then((response) => {
            this.selectList = response.data.menuList
            const zeroNode = {
              icon: '',
              list: null,
              menuId: '0',
              name: '无',
              open: null,
              orderNum: 0,
              parentId: null,
              parentName: null,
              perms: null,
              type: 0,
              url: ''
            }
            this.selectList.push(zeroNode)
          })
          this.$store.dispatch('permission/refreshRoute')

          const tableData = deepClone(this.list)
          let resTableData = []
          resTableData = this.buildTree(tableData)
          for (const i in resTableData) {
            resTableData[i].expand = false
          }
          this.tableData = resTableData
          // Just to simulate the time of the request
          this.listLoading = false
          resolve(true)
        }).catch(error => {
          console.log(error)
          this.$message({
            message: error,
            type: 'error'
          })
          reject(false)
        })
      }
      )
    },
    // 表格选中时触发
    handleSelectionChange(selection) {
      this.delIdArr = []
      if (selection.length) {
        this.disabledDelBtn = false
        for (const i in selection) {
          this.delIdArr.push(selection[i].menuId)
        }
      } else {
        this.disabledDelBtn = true
      }
      console.log(this.delIdArr)
    },
    // 初始化表单
    resetTemp() {
      console.log(this.temp, this.optionData)
      this.temp = {
        menuId: undefined,
        type: 0,
        parentId: '0',
        name: '',
        url: '',
        icon: 'no-pic',
        orderNum: 0,
        notes: '',
        status: 1
      }
    },
    // 刷新
    async handleRefresh() {
      console.log(this.optionData)
      if (await this.getList()) {
        this.$message({
          message: '刷新成功',
          type: 'success'
        })
      }
    },
    // 新增操作
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增数据接口
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveMenuInfo(this.temp).then((response) => {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 编辑操作
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // low copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据接口
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateMenuInfo(this.temp).then((response) => {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 删除操作
    handleDelete(idArr) {
      this.dialogDelVisible = true
      this.delIdArr = idArr
    },
    // 删除接口
    deleteData() {
      const flagArr = []
      this.delIdArr.forEach(id => {
        flagArr.push(this.checkHasChildren(id, this.tableData))
      })
      let flag = true
      for (const i in flagArr) {
        if (!flagArr[i]) {
          flag = false
          break
        }
      }
      if (flag) {
        deletMenuInfo(this.delIdArr).then(() => {
          this.dialogDelVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      } else {
        this.$message({
          message: '选择的菜单含有子菜单不可删除',
          type: 'warning'
        })
      }
    },
    // 回显选中的树形菜单
    checkHasChildren(id, data) {
      console.log(id, '23333')
      let flag = false
      data.forEach(item => {
        if (item.menuId === id) {
          if (!item.list) {
            flag = true
          } else {
            if (item.list.length === 0) {
              console.log(1)
              flag = true
            } else {
              console.log(2)
              flag = false
            }
          }
        }
      })
      return flag
    }
  }
}
</script>

<style lang="scss">
.app-container {
  .el-table {
    .gray-row {
      color: #c2d2d2;
    }
  }
  .el-button--mini{
    padding: 7px;
  }
  .filter-container{
    .filter-item {
      margin-left: 0;
      &.refresh-btn{
        background-color: #030303;
        color: azure;
      }
    }
  }
  .icon-catalog {

  }
  .icon-menu {
    margin-left: 20px;
  }
  .icon-button {
    margin-left: 40px;
  }
}
</style>
